package com.chuangmei.com.map;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

/**
 * 项目名称：HelloARObjectTracking
 * 类描述：方向传感器监听
 * 创建人：Administrator
 * 创建时间：2018/4/2 14:42
 * 修改人：Administrator
 * 修改时间：2018/4/2 14:42
 * 修改备注：
 */
public class MyOrientationListener implements SensorEventListener {

    private Context context;
    private SensorManager mSensorManager;

    private LocationClient mLocationClient;
    private Sensor mOrientationSensor;
    private OnOrientationListener onOrientationListener;
    private float direction;
    private int mTargetDirection;
    private int beforeDirection=0;

    public MyOrientationListener(Context context) {
        this.context = context;
    }


    // 开始
    public void start() {
        initLocation();
        initServices();
    }


    private void initLocation() {
        mLocationClient = new LocationClient(context);
        //mLocationClient.registerLocationListener(myListener);
        mLocationClient.start();
        LocationClientOption option = new LocationClientOption();
        option.setProdName("Compass");
        mLocationClient.setLocOption(option);
    }

    private void initServices() {
        // 传感器管理对象
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        // 传感器对象
        mOrientationSensor = mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION).get(0);
        // 注册
        if (mOrientationSensor != null) {
            mSensorManager.registerListener(this, mOrientationSensor,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    // 停止检测
    public void stop() {
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        direction = event.values[mSensorManager.DATA_X] * -1.0f;
        // 赋值给全局变量，让指南针旋转
        mTargetDirection = normalizeDegree(direction);

        if (Math.abs(mTargetDirection) != beforeDirection) {
            onOrientationListener.onOrientationChanged(mTargetDirection);
            beforeDirection = mTargetDirection;
        }

    }

    // 调整方向传感器获取的值
    private int normalizeDegree(float degree) {
        return (int) (degree + 720) % 360;
    }


    public void setOnOrientationListener(OnOrientationListener onOrientationListener) {
        this.onOrientationListener = onOrientationListener;
    }

    public interface OnOrientationListener {
        void onOrientationChanged(float x);
    }


}
